//
//  StringExtension.swift
//  SwiftTool
//
//  Created by 红沙尘 on 2018/11/25.
//  Copyright © 2018年 红沙尘. All rights reserved.
//

import Foundation
import UIKit

extension String {
    
    
    /// 获取文字宽高
    ///
    /// - Parameters:
    ///   - font: 文字的字体
    ///   - size: 给定的范围计算宽高
    /// - Returns: 得到的文字宽高
    func size(font:UIFont, size:CGSize) -> CGSize{
        let dic = [NSAttributedStringKey.font:font] // swift 3.0

        return self.boundingRect(with: size,
                                 options: [.usesLineFragmentOrigin],
                                 attributes: dic,
                                 context:nil).size
    }
    
    func nsRange(from range: Range<String.Index>) -> NSRange? {
        
        let utf16view = self.utf16
        
        if let from = range.lowerBound.samePosition(in: utf16view), let to = range.upperBound.samePosition(in: utf16view) {
            
                return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to))
        }
        
        return nil
    }
}
